#!/usr/bin/env python3
# vim: tabstop=4 expandtab

import re
from os import getenv
import antennaDB
import signoffs
import datetime
import hashlib

def getHashes(query = ""):
    hashes = []
    p = re.compile('^[a-zA-Z\d]{10}$')
    if query:
        parts = query.split('&')
        for part in parts:
            if p.match(part):
                hashes.append(part)
    return hashes

def urlHash(url = ""):
    hashObject = hashlib.md5(url.encode())
    return hashObject.hexdigest()[0:10]

def filteredEntries(hashes = [], entries = []):
    filtered = []
    for entry in entries:
        if not urlHash(entry.feedurl) in hashes:
            filtered.append(entry)
    return filtered

def generatePage(hashes = [], entries = [], pathInfo = ""):
    fullPath = f"gemini://{getenv('SERVER_NAME')}{getenv('SCRIPT_NAME')}"
    print("20 text/gemini\r\n")

    if pathInfo == "config":
        print("# Configure Your Filter\n")

        print(f"=> {fullPath}?{'&'.join(hashes)} Your current filter.\n")
        feedurls= []
        for entry in entries:
            if entry.feedurl in feedurls:
                continue
            feedurls.append(entry.feedurl)
            feedurlHash = urlHash(entry.feedurl)
            if feedurlHash in hashes:
                tmphashes = hashes.copy()
                tmphashes.remove(feedurlHash)
                print(f"=> {fullPath}/config?{'&'.join(tmphashes)} Remove '{entry.feedurl}' from filter.")
            else:
                print(f"=> {fullPath}/config?{'&'.join(hashes + [feedurlHash])} Add '{entry.feedurl}' to filter.")

    else: # We're not configuring. Just reading.
        print("# Your Antenna View\n")
        print(f"=> {fullPath}/config?{'&'.join(hashes)} Configure your filter.")
        datestamp = "0000-00-00"
        for entry in filteredEntries(hashes, entries):
            timestamp = datetime.datetime.utcfromtimestamp(entry.updated).strftime('%Y-%m-%d')
            if not datestamp == timestamp:
                datestamp = timestamp
                print("")
            print(f"=> {entry.link} {timestamp} {entry.author}: {entry.title}")

    print(f"\n> {signoffs.getsig()}\n")

## MAIN ##

db = antennaDB.AntennaDB()
pathInfo = getenv('PATH_INFO')
queryString = getenv('QUERY_STRING')

if not pathInfo and not queryString:
    print("10 Would you like to create a filter? (y/yes or turn back)")
elif not pathInfo and queryString in ["y","yes"]:
    generatePage([], db.getEntries(), "config")
else:
    hashes = getHashes(queryString)
    generatePage(hashes, db.getEntries(), pathInfo)

